import { initArticleList } from '@/api/article'
import { useUserStore } from '@/store/modules/userStore'
import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { Ref } from 'vue'

export const usePageData = () => {
  const articleData: Ref<any[]> = ref([])

  const userStore = useUserStore()

  let limit = 0

  initArticleList({ userId: userStore.userInfo?.userId }).then(res => {
    res.data.map((v: AnyObject) => {
      let data = {}
      for (const key in v) {
        data = Object.assign(data, v[key])
      }
      articleData.value.push(data)
    })

    console.log(articleData.value);

  })

  let isLoad = false

  onReachBottom(() => {
    if (isLoad) {
      return false
    }

    isLoad = true

    setTimeout(() => {
      uni.request({
        method: 'POST',
        url: 'http://xuanxiaoqian.com:7777/article/getArticleLimit',
        data: {
          "startPage": limit += 5,
          "endPage": 5
        },
        success(result) {
          let count = 0
          const interval = setInterval(() => {
            // @ts-ignore
            articleData.value.push(result.data.data[count])
            count++

            // @ts-ignore
            if (count == result.data.data.length) {
              clearInterval(interval)
            }
          }, 100)
        },
        complete() {
          isLoad = false
        }
      })
    }, 500)
  })

  onPullDownRefresh(() => {
    limit = 0
    uni.request({
      method: 'POST',
      url: 'http://xuanxiaoqian.com:7777/article/getArticleLimit',
      data: {
        "startPage": limit,
        "endPage": 5
      },
      success(result) {
        // @ts-ignore
        articleData.value = result.data.data
      },
      complete() {
        uni.stopPullDownRefresh()
      }
    })
  })

  return { articleData }
}